package admin

import (
	"strconv"

	"github.com/labstack/echo/v4"
	"gorm.io/gorm"
	"techoiceness.com/aiagent/llm-gateway/internal/auth"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// 获取用户列表
func (h *AdminHandler) GetUsers(c echo.Context) error {
	var req GetUsersRequest
	req.Page, _ = strconv.Atoi(c.QueryParam("page"))
	if req.Page <= 0 {
		req.Page = 1
	}
	req.Limit, _ = strconv.Atoi(c.QueryParam("limit"))
	if req.Limit <= 0 || req.Limit > 100 {
		req.Limit = 20
	}

	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "Validation failed: "+err.Error())
	}

	var users []entity.User
	var total int64

	// 获取总数
	if err := h.db.Model(&entity.User{}).Count(&total).Error; err != nil {
		return response.InternalServerError(c, "Database error")
	}

	// 获取用户列表
	offset := (req.Page - 1) * req.Limit
	if err := h.db.Offset(offset).Limit(req.Limit).Order("created_at DESC").Find(&users).Error; err != nil {
		return response.InternalServerError(c, "Database error")
	}

	// 转换为响应格式
	rows := make([]UserRow, 0, len(users))
	for _, user := range users {
		rows = append(rows, UserRow{
			ID:        user.ID,
			Username:  user.Username,
			CreatedAt: user.CreatedAt.Unix(),
			UpdatedAt: user.UpdatedAt.Unix(),
		})
	}

	// 转换为[]interface{}
	interfaceRows := make([]interface{}, len(rows))
	for i, row := range rows {
		interfaceRows[i] = row
	}

	return response.Paginated(c, interfaceRows, total, req.Page, req.Limit)
}

// 获取用户详情
func (h *AdminHandler) GetUserDetail(c echo.Context) error {
	var req GetUserDetailRequest

	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}
	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "Validation failed: "+err.Error())
	}

	userID := req.ID

	var user entity.User
	if err := h.db.Where("id = ?", userID).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return response.NotFound(c, "User not found")
		}
		return response.InternalServerError(c, "Database error")
	}

	// 获取用户的对话数量
	var conversationCount int64
	h.db.Model(&entity.Conversation{}).Where("user_id = ?", userID).Count(&conversationCount)

	// 获取用户的消息数量
	var messageCount int64
	h.db.Model(&entity.ClientMessage{}).Where("user_id = ?", userID).Count(&messageCount)

	responseData := GetUserDetailResponse{
		ID:                user.ID,
		Username:          user.Username,
		ConversationCount: conversationCount,
		MessageCount:      messageCount,
		CreatedAt:         user.CreatedAt.Unix(),
		UpdatedAt:         user.UpdatedAt.Unix(),
	}

	return response.Success(c, responseData)
}

// 创建用户
func (h *AdminHandler) CreateUser(c echo.Context) error {
	var req CreateUserRequest
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "Invalid request body")
	}

	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "Validation failed: "+err.Error())
	}

	// 检查用户名是否已存在
	var existingUser entity.User
	if err := h.db.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
		return response.Conflict(c, "Username already exists")
	} else if err != gorm.ErrRecordNotFound {
		return response.InternalServerError(c, "Database error")
	}

	// 加密密码
	hashedPassword, err := auth.PasswordHash(req.Password)
	if err != nil {
		return response.InternalServerError(c, "Failed to hash password")
	}

	// 创建用户
	user := &entity.User{
		Username:     req.Username,
		PasswordHash: hashedPassword,
	}

	if err := h.db.Create(user).Error; err != nil {
		return response.InternalServerError(c, "Failed to create user")
	}

	responseData := CreateUserResponse{
		ID:       user.ID,
		Username: user.Username,
	}

	return response.Success(c, &responseData)
}

// 更新用户
func (h *AdminHandler) UpdateUser(c echo.Context) error {
	var req UpdateUserRequest
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "Validation failed: "+err.Error())
	}

	userID := req.ID

	// 获取现有用户
	var user entity.User
	if err := h.db.Where("id = ?", userID).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return response.NotFound(c, "User not found")
		}
		return response.InternalServerError(c, "Database error")
	}

	// 更新用户名
	if req.Username != nil && *req.Username != user.Username {
		// 检查新用户名是否已存在
		var existingUser entity.User
		if err := h.db.Where("username = ? AND id != ?", *req.Username, userID).First(&existingUser).Error; err == nil {
			return response.Conflict(c, "Username already exists")
		} else if err != gorm.ErrRecordNotFound {
			return response.InternalServerError(c, "Database error")
		}
		user.Username = *req.Username
	}

	// 更新密码
	if req.Password != nil {
		hashedPassword, err := auth.PasswordHash(*req.Password)
		if err != nil {
			return response.InternalServerError(c, "Failed to hash password")
		}
		user.PasswordHash = hashedPassword
	}

	// 保存更新
	if err := h.db.Save(&user).Error; err != nil {
		return response.InternalServerError(c, "Failed to update user")
	}

	return response.Success(c, map[string]string{
		"message": "User updated successfully",
	})
}

// 删除用户
func (h *AdminHandler) DeleteUser(c echo.Context) error {
	var req DeleteUserRequest
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "Validation failed: "+err.Error())
	}

	userID := req.ID

	// 检查用户是否存在
	var user entity.User
	if err := h.db.Where("id = ?", userID).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return response.NotFound(c, "User not found")
		}
		return response.InternalServerError(c, "Database error")
	}

	// 开始事务删除用户及其相关数据
	tx := h.db.Begin()
	if tx.Error != nil {
		return response.InternalServerError(c, "Failed to start transaction")
	}
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 删除用户的消息
	if err := tx.Where("user_id = ?", userID).Delete(&entity.ClientMessage{}).Error; err != nil {
		tx.Rollback()
		return response.InternalServerError(c, "Failed to delete user messages")
	}

	// 删除用户的对话
	if err := tx.Where("user_id = ?", userID).Delete(&entity.Conversation{}).Error; err != nil {
		tx.Rollback()
		return response.InternalServerError(c, "Failed to delete user conversations")
	}

	// 删除用户
	if err := tx.Delete(&user).Error; err != nil {
		tx.Rollback()
		return response.InternalServerError(c, "Failed to delete user")
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return response.InternalServerError(c, "Failed to commit transaction")
	}

	return response.Success(c, map[string]string{
		"message": "User deleted successfully",
	})
}

// 重置用户密码
func (h *AdminHandler) ResetUserPassword(c echo.Context) error {
	var req ResetPasswordRequest
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "Validation failed: "+err.Error())
	}

	userID := req.ID

	// 检查用户是否存在
	var user entity.User
	if err := h.db.Where("id = ?", userID).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return response.NotFound(c, "User not found")
		}
		return response.InternalServerError(c, "Database error")
	}

	// 加密新密码
	hashedPassword, err := auth.PasswordHash(req.NewPassword)
	if err != nil {
		return response.InternalServerError(c, "Failed to hash password")
	}

	// 更新密码
	user.PasswordHash = hashedPassword
	if err := h.db.Save(&user).Error; err != nil {
		return response.InternalServerError(c, "Failed to reset password")
	}

	return response.Success(c, map[string]string{
		"message": "Password reset successfully",
	})
}
